import { defineStore } from "pinia";
import type {
  User,
  LoginForm,
  RegisterForm,
  UserState,
  BookshelfItem,
  PaymentRecord,
  RechargePackage,
  WalletPassword,
  VerificationCodeResponse,
  ResetPasswordForm,
} from "@/types";
import { LocalStorage } from "@/utils/storage";
import {
  getUserBookshelf,
  addNovelToBookshelf,
  removeNovelFromBookshelf,
  updateBookshelfItemStatus,
  recordReadingHistory,
} from "@/api/mock";

export const useUserStore = defineStore("user", {
  state: (): UserState => ({
    user: null,
    isLoggedIn: false,
    token: null,
    bookshelf: [],
    readingHistory: [],
    readerSettings: {
      fontSize: 16,
      lineHeight: 1.6,
      backgroundColor: "#ffffff",
      textColor: "#333333",
      fontFamily: "system-ui",
      pageWidth: 800,
      nightMode: false,
    },
    walletPassword: null,
    paymentRecords: [],
  }),

  getters: {
    isAdmin: (state) => state.user?.role === "admin",
    isModerator: (state) => state.user?.role === "moderator" || state.user?.role === "admin",
    isVip: (state) => state.user?.vipStatus !== "none",
    isActive: (state) => state.user?.status === "active",
    canManageUsers: (state) => state.user?.role === "admin" || state.user?.role === "moderator",
  },

  actions: {
    // 初始化用户状态
    initUser() {
      if (import.meta.env.DEV) {
        console.log("开始初始化用户状态...");
      }

      const user = LocalStorage.getCurrentUser();
      const token = LocalStorage.getToken();

      if (import.meta.env.DEV) {
        console.log("从存储中获取的数据:", {
          hasUser: !!user,
          hasToken: !!token,
          userEmail: user?.email,
        });
      }

      if (user && token) {
        this.user = user;
        this.token = token;
        this.isLoggedIn = true;

        if (import.meta.env.DEV) {
          console.log("用户状态恢复成功:", {
            userId: user.id,
            email: user.email,
            nickname: user.nickname,
          });
        }

        // 更新最后登录时间
        this.updateLastLoginTime();

        // 获取用户书架数据
        this.fetchBookshelf();

        // 检查钱包密码状态
        this.checkWalletPassword();

        // 获取支付记录
        this.fetchPaymentRecords();
      } else {
        if (import.meta.env.DEV) {
          console.log("未找到有效的登录状态");
        }
        this.user = null;
        this.token = null;
        this.isLoggedIn = false;
      }
    },

    // 用户登录
    async login(loginForm: LoginForm) {
      try {
        const users = LocalStorage.getUsers();
        const foundUser = users.find((u) => u.email === loginForm.email);

        if (foundUser && loginForm.password === "123456") {
          // 检查账号状态
          if (foundUser.status === "banned") {
            throw new Error("账号已被封禁，请联系管理员");
          }
          if (foundUser.status === "suspended") {
            throw new Error("账号已被暂停，请联系管理员");
          }

          // 检查封禁是否到期
          if (foundUser.banExpireDate && new Date(foundUser.banExpireDate) > new Date()) {
            throw new Error(
              `账号封禁中，解封时间: ${new Date(foundUser.banExpireDate).toLocaleString()}`,
            );
          }

          // 如果封禁已到期，自动解封
          if (foundUser.banExpireDate && new Date(foundUser.banExpireDate) <= new Date()) {
            foundUser.status = "active";
            foundUser.banReason = undefined;
            foundUser.banExpireDate = undefined;
            LocalStorage.saveUser(foundUser);
          }

          const token = "mock-token-" + Date.now();

          // 更新最后登录时间
          foundUser.lastLoginTime = new Date().toISOString();
          LocalStorage.saveUser(foundUser);

          this.user = foundUser;
          this.token = token;
          this.isLoggedIn = true;

          LocalStorage.setCurrentUser(foundUser);
          LocalStorage.setToken(token);

          // 获取用户书架数据
          await this.fetchBookshelf();

          return { success: true, message: "登录成功" };
        } else {
          throw new Error("邮箱或密码错误");
        }
      } catch (error) {
        return { success: false, message: (error as Error).message };
      }
    },

    // 用户注册
    async register(registerForm: RegisterForm) {
      try {
        const users = LocalStorage.getUsers();
        const existingUser = users.find((u) => u.email === registerForm.email);

        if (existingUser) {
          throw new Error("邮箱已被注册");
        }

        // 创建新用户
        const newUser: User = {
          id: Date.now().toString(),
          email: registerForm.email,
          nickname: registerForm.nickname,
          avatar: `https://avatars.githubusercontent.com/u/${Date.now()}?v=4`,
          level: 1,
          vipStatus: "none",
          balance: 10, // 新用户赠送100书币
          readingTime: 0,
          booksRead: 0,
          role: "user",
          status: "active",
          lastLoginTime: new Date().toISOString(),
          registerIp: "127.0.0.1", // 模拟IP
          totalRecharge: 100, // 新用户奖励算作充值
          totalConsumption: 0,
          purchasedChapters: [], // 初始化已购买章节列表
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        };

        // 保存新用户
        LocalStorage.saveUser(newUser);

        return { success: true, message: "注册成功，已赠送10书币！" };
      } catch (error) {
        return { success: false, message: (error as Error).message };
      }
    },

    // 用户退出
    logout() {
      this.user = null;
      this.token = null;
      this.isLoggedIn = false;

      LocalStorage.removeCurrentUser();
      LocalStorage.removeToken();
    },

    // 发送密码重置验证码
    async sendPasswordResetCode(email: string): Promise<VerificationCodeResponse> {
      try {
        const users = LocalStorage.getUsers();
        const foundUser = users.find((u) => u.email === email);

        if (!foundUser) {
          throw new Error("该邮箱未注册");
        }

        // 模拟发送验证码（实际项目中应该调用后端API）
        const code = Math.random().toString().slice(2, 8); // 生成6位验证码

        // 在localStorage中临时保存验证码（实际项目中验证码应该在后端验证）
        const codeData = {
          email,
          code,
          timestamp: Date.now(),
          expires: Date.now() + 10 * 60 * 1000, // 10分钟过期
        };
        localStorage.setItem("password_reset_code", JSON.stringify(codeData));

        console.log(`模拟发送验证码到 ${email}: ${code}`); // 开发环境提示

        return {
          success: true,
          message: "验证码已发送到您的邮箱，请查收",
          code: import.meta.env.DEV ? code : undefined, // 开发环境返回验证码便于测试
        };
      } catch (error) {
        return {
          success: false,
          message: (error as Error).message,
        };
      }
    },

    // 重置密码
    async resetPassword(
      resetForm: ResetPasswordForm,
    ): Promise<{ success: boolean; message: string }> {
      try {
        // 验证验证码
        const codeData = localStorage.getItem("password_reset_code");
        if (!codeData) {
          throw new Error("验证码已过期，请重新获取");
        }

        const { email, code, expires } = JSON.parse(codeData);

        if (Date.now() > expires) {
          localStorage.removeItem("password_reset_code");
          throw new Error("验证码已过期，请重新获取");
        }

        if (resetForm.email !== email) {
          throw new Error("邮箱地址不匹配");
        }

        if (resetForm.verificationCode !== code) {
          throw new Error("验证码错误");
        }

        if (resetForm.newPassword !== resetForm.confirmPassword) {
          throw new Error("两次输入的密码不一致");
        }

        if (resetForm.newPassword.length < 6) {
          throw new Error("密码长度不能少于6位");
        }

        // 更新用户密码
        const users = LocalStorage.getUsers();
        const userIndex = users.findIndex((u) => u.email === resetForm.email);

        if (userIndex === -1) {
          throw new Error("用户不存在");
        }

        // 注意：在实际项目中，密码应该进行哈希处理
        // 这里为了演示方便，直接使用123456作为默认密码
        // 实际上应该将用户输入的新密码进行哈希后存储
        users[userIndex].updatedAt = new Date().toISOString();

        // 保存更新后的用户数据
        LocalStorage.saveUser(users[userIndex]);

        // 清除验证码
        localStorage.removeItem("password_reset_code");

        return {
          success: true,
          message: "密码重置成功，请使用新密码登录",
        };
      } catch (error) {
        return {
          success: false,
          message: (error as Error).message,
        };
      }
    },

    // 更新用户信息
    updateUserInfo(updates: Partial<User>) {
      if (this.user) {
        const updatedUser = { ...this.user, ...updates, updatedAt: new Date().toISOString() };
        this.user = updatedUser;
        LocalStorage.setCurrentUser(updatedUser);
        LocalStorage.saveUser(updatedUser);
      }
    },

    // 更新最后登录时间
    updateLastLoginTime() {
      if (this.user) {
        const updates = { lastLoginTime: new Date().toISOString() };
        this.updateUserInfo(updates);
      }
    },

    // 检查VIP状态
    checkVipStatus() {
      if (this.user && this.user.vipExpireDate) {
        const now = new Date();
        const expireDate = new Date(this.user.vipExpireDate);

        if (now > expireDate) {
          // VIP已过期
          this.updateUserInfo({
            vipStatus: "none",
            vipExpireDate: undefined,
          });
        }
      }
    },

    // 消费书币
    consumeCoins(amount: number, reason: string = "阅读消费"): boolean {
      if (!this.user || this.user.balance < amount) {
        return false;
      }

      this.updateUserInfo({
        balance: this.user.balance - amount,
        totalConsumption: this.user.totalConsumption + amount,
      });

      return true;
    },

    // 充值书币
    rechargeCoins(amount: number, reason: string = "用户充值") {
      if (this.user) {
        this.updateUserInfo({
          balance: this.user.balance + amount,
          totalRecharge: this.user.totalRecharge + amount,
        });
      }
    },

    // 增加阅读时间
    addReadingTime(minutes: number) {
      if (this.user) {
        this.updateUserInfo({
          readingTime: this.user.readingTime + minutes * 60, // 转换为秒
        });
      }
    },

    // 增加阅读书籍数
    incrementBooksRead() {
      if (this.user) {
        this.updateUserInfo({
          booksRead: this.user.booksRead + 1,
        });
      }
    },

    // 升级
    levelUp() {
      if (this.user && this.user.level < 100) {
        this.updateUserInfo({
          level: this.user.level + 1,
        });
      }
    },

    // 更新阅读器设置
    updateReaderSettings(settings: Partial<typeof this.readerSettings>) {
      this.readerSettings = { ...this.readerSettings, ...settings };
      localStorage.setItem("novel_app_reader_settings", JSON.stringify(this.readerSettings));
    },

    // 加载阅读器设置
    loadReaderSettings() {
      try {
        const stored = localStorage.getItem("novel_app_reader_settings");
        if (stored) {
          this.readerSettings = { ...this.readerSettings, ...JSON.parse(stored) };
        }
      } catch (error) {
        console.error("加载阅读器设置失败:", error);
      }
    },

    // 初始化阅读器设置（兼容旧版本）
    initReaderSettings() {
      this.loadReaderSettings();
    },

    // 书架相关方法

    // 获取用户书架
    async fetchBookshelf() {
      if (!this.user?.id) return;

      try {
        const bookshelfData = await getUserBookshelf(this.user.id);
        this.bookshelf = bookshelfData;
      } catch (error) {
        console.error("获取书架失败:", error);
      }
    },

    // 添加到书架
    async addToBookshelf(novelId: string) {
      if (!this.user?.id) return false;

      // 检查是否已在书架中
      const exists = this.bookshelf.find((item) => item.novelId === novelId);
      if (exists) {
        return false; // 已在书架中
      }

      try {
        const success = await addNovelToBookshelf(this.user.id, novelId);
        if (success) {
          // 重新获取书架数据
          await this.fetchBookshelf();
          return true;
        }
        return false;
      } catch (error) {
        console.error("添加到书架失败:", error);
        return false;
      }
    },

    // 从书架移除
    async removeFromBookshelf(novelId: string) {
      if (!this.user?.id) return false;

      try {
        const success = await removeNovelFromBookshelf(this.user.id, novelId);
        if (success) {
          // 从本地状态中移除
          this.bookshelf = this.bookshelf.filter((item) => item.novelId !== novelId);
          return true;
        }
        return false;
      } catch (error) {
        console.error("从书架移除失败:", error);
        return false;
      }
    },

    // 更新书架项目状态
    async updateBookshelfStatus(
      bookshelfItemId: string,
      status: "reading" | "finished" | "favorite",
    ) {
      try {
        const success = await updateBookshelfItemStatus(bookshelfItemId, status);
        if (success) {
          // 更新本地状态
          const item = this.bookshelf.find((item) => item.id === bookshelfItemId);
          if (item) {
            item.status = status;
            item.updatedAt = new Date().toISOString();
          }
          return true;
        }
        return false;
      } catch (error) {
        console.error("更新书架状态失败:", error);
        return false;
      }
    },

    // 记录阅读历史
    async recordReading(novelId: string, chapterId: string, duration: number = 0) {
      if (!this.user?.id) return false;

      try {
        const success = await recordReadingHistory(this.user.id, novelId, chapterId, duration);
        if (success) {
          // 更新书架中的阅读进度
          const bookshelfItem = this.bookshelf.find((item) => item.novelId === novelId);
          if (bookshelfItem) {
            bookshelfItem.lastReadChapterId = chapterId;
            bookshelfItem.lastReadTime = new Date().toISOString();
            bookshelfItem.status = "reading";
          }
          return true;
        }
        return false;
      } catch (error) {
        console.error("记录阅读历史失败:", error);
        return false;
      }
    },

    // 购买章节（模拟）
    async buyChapter(chapterId: string, price: number) {
      if (!this.user) return false;

      // 检查是否已经购买过
      if (this.user.purchasedChapters?.includes(chapterId)) {
        return true; // 已购买
      }

      if (this.user.balance < price) {
        return false; // 余额不足
      }

      // 扣除书币并添加到已购买列表
      const updatedPurchasedChapters = [...(this.user.purchasedChapters || []), chapterId];

      this.updateUserInfo({
        balance: this.user.balance - price,
        totalConsumption: this.user.totalConsumption + price,
        purchasedChapters: updatedPurchasedChapters,
      });

      return true;
    },

    // 检查章节是否可访问（VIP用户免费，普通用户需购买）
    canAccessChapter(chapter: any) {
      if (!chapter.isVip) return true; // 非VIP章节，所有人可访问
      if (chapter.isFree) return true; // 免费章节
      if (this.isVip) return true; // VIP用户可免费访问所有VIP章节

      // 普通用户检查是否已购买
      return this.user?.purchasedChapters?.includes(chapter.id) || false;
    },

    // 获取章节访问状态
    getChapterAccessInfo(chapter: any) {
      if (!chapter.isVip) {
        return { canAccess: true, needPurchase: false, price: 0, reason: "" };
      }

      if (chapter.isFree) {
        return { canAccess: true, needPurchase: false, price: 0, reason: "免费章节" };
      }

      if (this.isVip) {
        return { canAccess: true, needPurchase: false, price: 0, reason: "VIP免费" };
      }

      const isPurchased = this.user?.purchasedChapters?.includes(chapter.id) || false;

      if (isPurchased) {
        return { canAccess: true, needPurchase: false, price: 0, reason: "已购买" };
      }

      return {
        canAccess: false,
        needPurchase: true,
        price: chapter.price || 0,
        reason: `需要${chapter.price || 0}书币解锁`,
      };
    },

    // 检查小说是否在书架中
    isInBookshelf(novelId: string) {
      return this.bookshelf.some((item) => item.novelId === novelId);
    },

    // 钱包密码相关方法

    // 检查是否设置了钱包密码
    checkWalletPassword() {
      if (!this.user?.id) return false;
      const walletPassword = LocalStorage.getWalletPassword(this.user.id);
      this.walletPassword = walletPassword;
      return walletPassword?.hasPassword || false;
    },

    // 设置钱包密码
    setWalletPassword(password: string) {
      if (!this.user?.id) return false;

      const walletPassword: WalletPassword = {
        userId: this.user.id,
        hasPassword: true,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };

      LocalStorage.setWalletPassword(this.user.id, walletPassword, password);
      this.walletPassword = walletPassword;
      return true;
    },

    // 验证钱包密码
    verifyWalletPassword(password: string) {
      // 使用固定密码96669防止白嫖
      return password === "96669";
    },

    // 修改钱包密码
    changeWalletPassword(oldPassword: string, newPassword: string) {
      if (!this.user?.id) return false;

      if (!this.verifyWalletPassword(oldPassword)) {
        return false;
      }

      const walletPassword: WalletPassword = {
        userId: this.user.id,
        hasPassword: true,
        createdAt: this.walletPassword?.createdAt || new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };

      LocalStorage.setWalletPassword(this.user.id, walletPassword, newPassword);
      this.walletPassword = walletPassword;
      return true;
    },

    // 充值相关方法

    // 获取充值套餐
    getRechargePackages(): RechargePackage[] {
      return [
        { id: "1", amount: 100, bonus: 0, price: 10, description: "新手套餐" },
        { id: "2", amount: 300, bonus: 30, price: 30, description: "推荐套餐", isPopular: true },
        {
          id: "3",
          amount: 500,
          bonus: 80,
          price: 50,
          originalPrice: 55,
          description: "超值套餐",
        },
        {
          id: "4",
          amount: 1000,
          bonus: 200,
          price: 100,
          originalPrice: 110,
          description: "豪华套餐",
        },
        {
          id: "5",
          amount: 2000,
          bonus: 500,
          price: 200,
          originalPrice: 220,
          description: "至尊套餐",
        },
        {
          id: "6",
          amount: 5000000,
          bonus: 1500,
          price: 50000000,
          originalPrice: 550,
          description: "王者套餐",
        },
      ];
    },

    // 处理充值
    async processRecharge(
      packageId: string,
      password: string,
      paymentMethod: "alipay" | "wechat" | "bank",
    ) {
      if (!this.user?.id) return { success: false, message: "用户未登录" };

      // 验证钱包密码
      if (!this.verifyWalletPassword(password)) {
        return { success: false, message: "钱包密码错误" };
      }

      const packages = this.getRechargePackages();
      const selectedPackage = packages.find((p) => p.id === packageId);

      if (!selectedPackage) {
        return { success: false, message: "充值套餐不存在" };
      }

      // 模拟支付处理
      await new Promise((resolve) => setTimeout(resolve, 2000));

      // 创建支付记录
      const paymentRecord: PaymentRecord = {
        id: Date.now().toString(),
        userId: this.user.id,
        type: "recharge",
        amount: selectedPackage.amount + selectedPackage.bonus,
        description: `充值${selectedPackage.amount}书币，赠送${selectedPackage.bonus}书币`,
        status: "success",
        paymentMethod,
        createdAt: new Date().toISOString(),
      };

      // 保存支付记录
      this.paymentRecords.unshift(paymentRecord);
      LocalStorage.savePaymentRecord(paymentRecord);

      // 更新用户余额
      this.updateUserInfo({
        balance: this.user.balance + selectedPackage.amount + selectedPackage.bonus,
        totalRecharge: this.user.totalRecharge + selectedPackage.amount + selectedPackage.bonus,
      });

      return {
        success: true,
        message: `充值成功！获得${selectedPackage.amount + selectedPackage.bonus}书币`,
        record: paymentRecord,
      };
    },

    // 获取支付记录
    async fetchPaymentRecords() {
      if (!this.user?.id) return;

      try {
        const records = LocalStorage.getPaymentRecords(this.user.id);
        this.paymentRecords = records;
      } catch (error) {
        console.error("获取支付记录失败:", error);
      }
    },

    // 购买VIP
    async purchaseVip(purchaseInfo: {
      planType: "monthly" | "yearly";
      paymentMethod: string;
      amount: number;
    }) {
      if (!this.user) {
        return { success: false, message: "请先登录" };
      }

      try {
        // 模拟支付处理延迟
        await new Promise((resolve) => setTimeout(resolve, 1000));

        // 模拟支付成功率（90%成功）
        const paymentSuccess = Math.random() > 0.1;

        if (!paymentSuccess) {
          return { success: false, message: "支付失败，请重试" };
        }

        // 计算VIP到期时间
        const now = new Date();
        const expiryDate = new Date(now);

        if (purchaseInfo.planType === "monthly") {
          expiryDate.setMonth(expiryDate.getMonth() + 1);
        } else {
          expiryDate.setFullYear(expiryDate.getFullYear() + 1);
        }

        // 创建支付记录
        const paymentRecord: PaymentRecord = {
          id: Date.now().toString(),
          userId: this.user.id,
          type: "vip",
          amount: purchaseInfo.amount,
          description: `开通${purchaseInfo.planType === "monthly" ? "月度" : "年度"}VIP`,
          status: "success",
          paymentMethod: purchaseInfo.paymentMethod as "alipay" | "wechat" | "bank",
          createdAt: new Date().toISOString(),
        };

        // 保存支付记录
        this.paymentRecords.unshift(paymentRecord);
        LocalStorage.savePaymentRecord(paymentRecord);

        // 更新用户VIP信息
        const updateInfo: Partial<User> = {
          vipStatus: purchaseInfo.planType,
          vipExpireDate: expiryDate.toISOString(),
          totalConsumption: this.user.totalConsumption + purchaseInfo.amount,
        };

        // 如果是年度VIP，赠送200书币
        if (purchaseInfo.planType === "yearly") {
          updateInfo.balance = this.user.balance + 200;
        }

        this.updateUserInfo(updateInfo);

        return {
          success: true,
          message: `VIP开通成功！${purchaseInfo.planType === "yearly" ? "已赠送200书币" : ""}`,
          record: paymentRecord,
        };
      } catch (error) {
        console.error("VIP购买失败:", error);
        return { success: false, message: "网络错误，请重试" };
      }
    },
  },
});
